use diesel::prelude::*;
use diesel::MysqlConnection;

use super::model::*;
use crate::database::{crud, schema::link, DbError};
use crate::db_create;
use crate::db_update;
use crate::{db_delete, db_read_count_from_offset_by_field};

db_create!(link, Link, NewLink, create);
db_read_count_from_offset_by_field!(link, Link, read_count_from_offset_by_tid, tid, i32);
db_update!(link, NewLink, update);
db_delete!(link, delete);

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        database::{
            self, establish_connection,
            table::{category::model::NewCategory, tag::model::NewTag},
        },
        db_create, db_read, test_db_create, test_db_delete, test_db_reads_by_field,
    };
    use diesel::Connection;

    db_create!(link, Link, NewLink, create);
    db_read!(link, Link, read);

    fn insert_test_data(conn: &mut MysqlConnection) -> (i32, i32, i32) {
        let category_id = database::table::category::crud::create(
            conn,
            NewCategory {
                name: "CATE",
                desc: "DESC",
                cover: "COVER",
                slug: "LINK",
            },
        )
        .unwrap();
        let tag_id = database::table::tag::crud::create(
            conn,
            NewTag {
                name: "TAG1",
                desc: "DESC1",
                avatar: "AVATAR1",
                slug: "LINK1",
                cid: category_id,
            },
        )
        .unwrap();
        let link_id1 = create(
            conn,
            NewLink {
                platform: "PLATFORM1",
                url: "URL1",
                tid: tag_id,
            },
        )
        .unwrap();
        let link_id2 = create(
            conn,
            NewLink {
                platform: "PLATFORM2",
                url: "URL2",
                tid: tag_id,
            },
        )
        .unwrap();
        (link_id1, link_id2, tag_id)
    }

    test_db_create!();
    test_db_reads_by_field!(test_read_by_tid, read_count_from_offset_by_tid, 2);
    test_db_delete!();
}
